<?php

require_once ROOT_DIR.'models/Todo.php';
require_once ROOT_DIR.'models/Workinterval.php';
require_once ROOT_DIR.'controls/RightHelper.php';

/**
 * Stores the given working interval
 * @param int $todoID
 * @param int $userID
 * @param timestamp $startDate
 * @param timestamp $endDate
 */
function addWorkinterval($todoID, $userID, $startDate, $endDate){
	
	if(is_null($userID)) $userID = $_SESSION['USER_ID'];
	
	$user = User::getUser($userID);
	$todo = Todo::getTodo($todoID);
	
	if(!is_null($user)){
		if(!is_null($todo)){
			if($_SESSION['USER_NAME'] == 'admin' || ($userID == $_SESSION['USER_ID'] && RightHelper::checkIfLinkedToTodo($todo, true))){
				$wi = new Workinterval($userID, $todoID, $startDate, $endDate);
				if($wi->saveToDB()){
					$res = new ResultJSON(false, session_id());
					$res->addItem('wID', $wi->getID());
					echo $res->renderView();
				} else {
					$res = new ResultJSON(true, session_id(), ERROR_ACTION_FAILED);
					echo $res->renderView();
				}
			} else {
				$res = new ResultJSON(true, session_id(), ERROR_NOT_ALLOWED);
				echo $res->renderView();
			}
		} else {
			$res = new ResultJSON(true, session_id(), ERROR_TODO_DOES_NOT_EXIST);
			echo $res->renderView();
		}
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_USER_DOES_NOT_EXIST);
		echo $res->renderView();
	}
}

?>